-- $Id: bookmarks.lua 47 2008-07-11 23:07:35Z dtikhonov $
--
-- bookmarks class.

Bookmarks = {}

function Bookmarks:new (obj)
    obj = obj or {}
    setmetatable(obj, self)
    self.__index = self
    self['bookmarks'] = {}
    return obj
end

function Bookmarks:add (name, location)
    if (self:get_by_name(name)) then return false end
    local sz = table.getn(self.bookmarks)
    self.bookmarks[sz + 1] = { name=name, location=location, }
    return true
end

function Bookmarks:delete_all ()
    self['bookmarks'] = {}
end

function Bookmarks:count ()
    return table.getn(self.bookmarks)
end

function Bookmarks:get_by_name (name)
    for i in pairs(self.bookmarks) do
        if self.bookmarks[i].name == name then
            return self.bookmarks[i]
        end
    end
    return nil
end

function Bookmarks:get_by_number (number)
    if table.getn(self.bookmarks) < number then return nil end
    return self.bookmarks[number]
end

function Bookmarks:debug_print ()
    for i in pairs(self.bookmarks) do
        print(i .. ": " .. self.bookmarks[i].name .. " -> "
                .. self.bookmarks[i].location)
    end
end

function Bookmarks:serialize (fh)
    fh:write("-- autogenerated by dhexview\n--\n")
    fh:write("bookmarks {\n")
    for i in pairs(self.bookmarks) do
        fh:write("  { name="   ..
                        string.format("%q", self.bookmarks[i].name)
               ..  ", location=" ..
                        string.format("0x%X", self.bookmarks[i].location)
               .. ", },\n")
    end
    fh:write("}\n");
    fh:write("-- vim:ft=lua:\n")
end

--[[
b = Bookmarks:new();
b:add("duh", 67823);
b:add("abc", 123);
b:debug_print();
location = b:get_by_name("abc")
print(location.location)
location = b:get_by_number(1)
print(location.name)
b:save("/tmp/f")
--]]

--[[
b = Bookmarks:new()
b:init_from_file("/tmp/f")
b:debug_print()
--]]
